import asyncio

import h5py
import numpy as np
from datetime import datetime, timedelta


def fmt_frm_id(id):
  return f'{id:0>6}'


async def taskInfo(request, json, **kw):
  task = request.args.task
  with h5py.File(task, 'r') as f:
    keys = [i for i in f.keys() if 'r' not in i]
    return json({"fmin": int(keys[0]), "fmax": int(keys[-1]), "tstart": f.attrs['start'], "tend": f.attrs['end']})
  return json({})


from sanic import response


async def sample(request, raw, **kw):
  args = request.args
  task = args.task
  igrp = (int(args.igrp) or slice(None)) if args.igrp else slice(None)
  ifrm = slice(None, None, int(args.ifrm) or None) if args.ifrm else slice(None)
  igrp = int(igrp)
  ts = datetime.strptime(args.s, '%Y-%m-%dT%H:%M:%S').timestamp()
  te = datetime.strptime(args.e, '%Y-%m-%dT%H:%M:%S').timestamp()

  async def inn(rsp: response.ResponseStream):
    with h5py.File(task, 'r') as tf:
      keys = []
      for k in tf.keys():
        d_ts = tf[k].attrs['ts']
        if d_ts < ts: continue
        if d_ts > te: break
        keys.append(k)
      keys.sort()
      for k in keys[::ifrm]:
        await rsp.write(tf[k][::igrp].tobytes())
        await asyncio.sleep(0)

  r = response.ResponseStream(inn, content_type='binary')
  r.request = request
  return r
  # '''


async def frmdata(request, raw, **kw):
  args = request.args
  task = args.get('task', None)
  frmid = args.get('frm', '1')
  # task = '/OMSDATA-TW2/20241231/GRAS1-00001/AMAG/.h5'

  with h5py.File(task, 'r') as f:
    id = fmt_frm_id(frmid)
    d = f[id][...]
    # d.dtype = '7 f8'
    print(d.shape)
    bytes = d.tobytes()
  return raw(bytes)


async def frminfo(request, json, **kw):
  args = request.args
  task = args.get('task', None)
  frmid = args.get('frm', '1')

  with h5py.File(task, 'r') as f:
    id = fmt_frm_id(frmid)
    d = f[id]
    return json(dict(d.attrs))

async def s(request, raw, **kw):

  dtype = [('t', 'f8'), ('ax', 'f8'), ('ay', 'f8'), ('az', 'f8'), ('bx', 'f8'), ('by', 'f8'), ('bz', 'f8')]
  args = request.args
  t = args.task
  inter = args.get('inter',1)

  m = args.m
  sStr = args.get('s','1970-01-01T00:00:00')
  eStr = args.get('e','9999-01-01T00:00:00')
  if len(sStr)==16:
    sStr = sStr+":00"
  if len(eStr) ==16:
    eStr = eStr+":00"
  ts = datetime.strptime(sStr+'+0800', '%Y-%m-%dT%H:%M:%S%z').timestamp()*1e3
  te = datetime.strptime(eStr+'+0800', '%Y-%m-%dT%H:%M:%S%z').timestamp()*1e3
  data = np.fromfile(f'{t}/.dat', dtype=dtype)
  print(f'{ts},{te},m:{np.max(data["t"])},x:{np.min(data["t"])}')
  tmask =  data['t']
  vali_data = data[(tmask >= ts) & (tmask <te+10)]
  slc = slice(None)
  if m=='g':
    inter = int(inter)
    inter=inter
    if inter:
      slc = slice(0, None, inter)
  print('--------------------------------')
  if m=='t':
    inter = float(inter)*1000
    if inter:
      print(f'v.shape:{vali_data.shape}, inter: {inter}')
      i_d = vali_data['t'] / inter
      print(f'i_d.shape: {i_d.shape}')
      v, i, c = np.unique(i_d.astype('i8'),
                          return_counts=1,
                          return_index=1)
      slc = i
      print(v,i,c)
  rst = vali_data[slc]

  print(rst.shape,inter, slc)
  # print(rst[0])
  print('--------------------------------')
  return raw(rst.tobytes())

